package com.portal.innovation.sysController;


import com.portal.innovation.utils.PageUtils;
import com.portal.innovation.common.R;
import com.portal.innovation.config.SysException;
import com.portal.innovation.pojo.FileList;
import com.portal.innovation.service.OSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/file")
public class OSSController {


    @Autowired
    private OSService service;

    @Value("${web.upload-path}")
    private String uploadPath;

    @PostMapping("upload")
    public R upload(MultipartFile file,
                    HttpServletRequest request) {
        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 比如：/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String format = sdf.format(new Date());
        File folder = new File(uploadPath +"photos/"+ format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径
            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + request.getContextPath() + "/photos/" + format + newName;

            FileList fileList = new FileList(filePath);
            service.save(fileList);

            return R.ok().put("url", filePath);
        } catch (IOException e) {
            e.printStackTrace();
            throw new SysException();
        }
    }

    //删除图片
    @DeleteMapping
    public R deleteFile(@RequestParam String fileUrl) {
        service.deleteFile(fileUrl);
        return R.ok();
    }

    @PostMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = service.queryPage(params);
        return R.ok().put("page", page);
    }

}
